﻿using HttpServer.Models;
using HttpServer.Restful;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace HttpServer.Controller
{
    [RoutePrefix("test/user")]
    public class UserController : ApiController
    {

        // 请求地址：http://127.0.0.1:8087/test/user/get
        [HttpGet]
        [Route("get")]
        public JsonResult GetUsers()
        {
            List<User> result = new List<User>();
            foreach (User user in FrmMain.users.Values)
            {
                result.Add(user);
            }

            return JsonResult.ok(result);
        }


        // 请求地址：http://127.0.0.1:8087/test/user/delete
        [HttpPost]
        [Route("delete")]
        public JsonResult DeleteUser([FromBody]User user)
        {
            if (user == null)
            {
                return JsonResult.fail("请求参数不能为空！");
            }
            if (!FrmMain.users.ContainsKey(user.Id))
            {
                return JsonResult.fail("不存在该user！");
            }

            if (!FrmMain.users.Remove(user.Id))
            {
                return JsonResult.fail("user删除失败！");
            }

            return JsonResult.ok("user删除成功！");
        }


        // 请求地址：http://127.0.0.1:8087/test/user/update
        [HttpPost]
        [Route("update")]
        public JsonResult UpdateUser([FromBody]User user)
        {
            if (user == null)
            {
                return JsonResult.fail("请求参数不能为空！");
            }
            if (!FrmMain.users.ContainsKey(user.Id))
            {
                return JsonResult.fail($"id为{user.Id}的user不存在！");
            }
            if (!string.IsNullOrWhiteSpace(user.Name))
            {
                FrmMain.users[user.Id].Name = user.Name;
            }
            if (user.Age > 0)
            {
                FrmMain.users[user.Id].Age = user.Age;
            }

            return JsonResult.ok("user修改成功！");
        }


        // 请求地址：http://127.0.0.1:8087/test/user/insert
        [HttpPost]
        [Route("insert")]
        public JsonResult InsertUser([FromBody]User user)
        {
            if (user == null)
            {
                return JsonResult.fail("请求参数不能为空！");
            }
            if (FrmMain.users.ContainsKey(user.Id))
            {
                return JsonResult.fail("此user的id已存在！");
            }
            FrmMain.users.Add(user.Id, user);


            return JsonResult.ok("user新增成功！");
        }
    }
}
